<template>
  <view class="translate-container">
    <view class="content-area">
      <view class="container">
        <!-- 语言选择区域 -->
        <view class="language-selector">
          <view class="source-lang">
            <picker :value="sourceLangIndex" :range="languages" range-key="name" @change="changeSourceLang">
              <view class="picker">
                <text>{{ languages[sourceLangIndex]?.name }}</text>
                <text class="arrow">▼</text>
              </view>
            </picker>
          </view>
          <view class="switch-btn" @tap="switchLanguages">
            <text class="iconfont">⇄</text>
          </view>
          <view class="target-lang">
            <picker :value="targetLangIndex" :range="languages" range-key="name" @change="changeTargetLang">
              <view class="picker">
                <text>{{ languages[targetLangIndex]?.name }}</text>
                <text class="arrow">▼</text>
              </view>
            </picker>
          </view>
        </view>

        <!-- 输入区域 -->
        <view class="input-area">
          <textarea
            v-model="sourceText"
            class="input-text"
            placeholder="请输入要翻译的文本"
            @input="onInput"
          ></textarea>
          <view class="input-tools">
            <text class="word-count">{{ sourceText.length }}/5000</text>
            <view class="tool-buttons">
              <button class="tool-btn" @tap="clearText">
                <text class="iconfont">🗑️</text>
              </button>
              <button class="tool-btn" @tap="pasteText">
                <text class="iconfont">📋</text>
              </button>
            </view>
          </view>
        </view>

        <!-- 翻译结果区域 -->
        <view class="result-area" v-if="translatedText">
          <view class="result-text">{{ translatedText }}</view>
          <view class="result-src">原文：{{ sourceText }}</view>
          <view class="result-tools">
            <button class="tool-btn" @tap="copyResult">
              <text class="iconfont">📋</text>
            </button>
            <button class="tool-btn" @tap="speakResult(translatedText)">
              <text class="iconfont">🔊</text>
            </button>
          </view>
        </view>

        <!-- 翻译按钮 -->
        <button 
          class="translate-btn" 
          :disabled="!sourceText" 
          :class="{ disabled: !sourceText }"
          @tap="translate"
        >
          翻译
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      languages: [],
      sourceLangIndex: 0,
      targetLangIndex: 1,
      sourceText: '',
      translatedText: '',
      isTranslating: false
    };
  },
  onLoad() {
    const langList = uni.getStorageSync('allLanguages') || [];
    this.languages = langList;
    const sIdx = uni.getStorageSync('sourceLangIndex');
    const tIdx = uni.getStorageSync('targetLangIndex');
    if (typeof sIdx === 'number' && sIdx < this.languages.length) this.sourceLangIndex = sIdx;
    if (typeof tIdx === 'number' && tIdx < this.languages.length) this.targetLangIndex = tIdx;
  },
  methods: {
    changeSourceLang(e) {
      this.sourceLangIndex = e.detail.value;
      uni.setStorageSync('sourceLangIndex', this.sourceLangIndex);
    },
    changeTargetLang(e) {
      this.targetLangIndex = e.detail.value;
      uni.setStorageSync('targetLangIndex', this.targetLangIndex);
    },
    switchLanguages() {
      const tmp = this.sourceLangIndex;
      this.sourceLangIndex = this.targetLangIndex;
      this.targetLangIndex = tmp;
      uni.setStorageSync('sourceLangIndex', this.sourceLangIndex);
      uni.setStorageSync('targetLangIndex', this.targetLangIndex);
    },
    onInput(e) {
      this.sourceText = e.detail.value;
    },
    clearText() {
      this.sourceText = '';
    },
    pasteText() {
      uni.getClipboardData({ success: res => { this.sourceText = res.data; } });
    },
    copyResult() {
      uni.setClipboardData({
        data: this.translatedText,
        success: () => uni.showToast({ title: '已复制', icon: 'none' })
      });
    },

    // 主逻辑：POST 获取 mp3 url 并播放
    async speakResult(text) {
      if (!text) {
        uni.showToast({ title: '无音频内容', icon: 'none' });
        return;
      }
      console.log('[DEBUG] speakResult called, text=', text);
      uni.showLoading({ title: '语音合成中...' });
      try {
        // 1. 请求后端获取 mp3 url
        const res = await uni.request({
          url: 'http://qixin.yeshan.fun/tts/url',
          method: 'POST',
          data: { text },
          header: { 'content-type': 'application/json' }
        });
        console.log('[DEBUG] tts/url 返回:', res);
        let url = '';
        if (res.statusCode === 200 && res.data && typeof res.data.url === 'string') {
          url = res.data.url;
          // 如果是相对路径，拼接域名
          if (url.startsWith('/')) {
            url = 'http://qixin.yeshan.fun' + url;
          }
        } else {
          uni.showToast({ title: '获取音频地址失败', icon: 'none' });
          uni.hideLoading();
          return;
        }
        // 2. 下载并播放
        console.log('[DEBUG] 获取到音频url:', url);
        uni.downloadFile({
          url: url,
          success: (dlRes) => {
            console.log('[DEBUG] downloadFile 成功:', dlRes.tempFilePath);
            uni.saveFile({
              tempFilePath: dlRes.tempFilePath,
              success: (saveRes) => {
                console.log('[DEBUG] 文件已保存:', saveRes.savedFilePath);
                const player = plus.audio.createPlayer(saveRes.savedFilePath);
                player.play(
                  () => {
                    console.log('[App] 播放完成');
                    uni.hideLoading();
                  },
                  err => {
                    console.error('[App] 播放失败', err);
                    uni.showToast({ title: '播放失败', icon: 'none' });
                    uni.hideLoading();
                  }
                );
              },
              fail: (e) => {
                console.error('[App] uni.saveFile 失败', e);
                uni.showToast({ title: '保存文件失败', icon: 'none' });
                uni.hideLoading();
              }
            });
          },
          fail: (e) => {
            console.error('[App] downloadFile 失败', e);
            uni.showToast({ title: '下载音频失败', icon: 'none' });
            uni.hideLoading();
          }
        });
      } catch (e) {
        console.error('[App] tts/url 请求异常', e);
        uni.showToast({ title: '请求异常', icon: 'none' });
        uni.hideLoading();
      }
    },

    // 翻译功能
    async translate() {
      if (!this.sourceText || this.isTranslating) return;
      this.isTranslating = true;
      uni.showLoading({ title: '翻译中...' });
      try {
        const from_lang = this.languages[this.sourceLangIndex]?.code || '';
        const to_lang = this.languages[this.targetLangIndex]?.code || '';
        const res = await uni.request({
          url: 'http://qixin.yeshan.fun/translate',
          method: 'POST',
          data: { text: this.sourceText, from_lang, to_lang },
          header: { 'content-type': 'application/json' }
        });
        if (res.statusCode === 200 && res.data?.result?.trans_result) {
          this.translatedText = res.data.result.trans_result.dst;
        } else {
          this.translatedText = '翻译失败';
        }
      } catch {
        this.translatedText = '翻译失败';
      } finally {
        this.isTranslating = false;
        uni.hideLoading();
      }
    }
  }
};
</script>

<style>
.translate-container {
    min-height: 100vh;
    background: #fff;
    padding: 40rpx 30rpx 30rpx 30rpx;
}
.content-area {
    width: 100%;
}
.container {
    width: 100%;
}
.language-selector {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
}
.source-lang, .target-lang {
    flex: 1;
}
.picker {
    padding: 16rpx 32rpx;
    background: #f5f5f5;
    border-radius: 12rpx;
    font-size: 30rpx;
    color: #333;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.arrow {
    font-size: 24rpx;
    color: #888;
}
.switch-btn {
    margin: 0 20rpx;
    font-size: 36rpx;
    color: #1976d2;
}
.input-area {
    width: 100%;
    margin-bottom: 30rpx;
}
.input-text {
    width: 100%;
    min-height: 120rpx;
    border: 1rpx solid #eee;
    border-radius: 12rpx;
    padding: 20rpx;
    font-size: 30rpx;
    background: #fafafa;
}
.input-tools {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10rpx;
}
.word-count {
    font-size: 24rpx;
    color: #888;
}
.tool-buttons {
    display: flex;
}
.tool-btn {
    background: none;
    border: none;
    padding: 10rpx;
    margin-left: 10rpx;
    font-size: 32rpx;
}
.result-area {
    background: #f8f9fa;
    border-radius: 12rpx;
    padding: 24rpx;
    margin-bottom: 30rpx;
}
.result-text {
    font-size: 32rpx;
    color: #1976d2;
    margin-bottom: 16rpx;
}
.result-src {
    font-size: 24rpx;
    color: #888;
    margin-bottom: 16rpx;
}
.result-tools {
    display: flex;
    justify-content: flex-end;
}
.translate-btn {
    width: 100%;
    height: 88rpx;
    background: linear-gradient(90deg, #4fc3f7, #1976d2);
    color: #fff;
    font-size: 32rpx;
    border-radius: 16rpx;
}
.translate-btn.disabled {
    background: #ccc;
    color: #fff;
}
</style> 